package libs.game.sokoban;

import libs.game.*;
import libs.game.sokoban.Path;

/**
 *              This class looks after marking fields which has a specific quality.
 *
 * @author      Jan Papousek
 * @version     2009-03-12
 */
public abstract class AbstractPath implements Path {

    protected Integer[][] path;

    protected int numOfPathFields = 0;

    @Override
    public int columns() {
        if (this.rows() > 0) {
            return this.path[0].length;
        } else {
            return 0;
        }
    }

    /**
     *          The class which extends this abstract class has to compute
     *          path before calling this method.
     *
     * @param   coord   Field coordinates.
     * @return  Path.
     */
    @Override
    public Integer get(Coordinates coord) {
        return path[coord.getY()][coord.getX()];
    }

    @Override
    public int getNumOfPathFields() {
        return numOfPathFields;
    }

    @Override
    public int rows() {
        return this.path.length;
    }

    @Override
    public String toString() {
        StringBuffer result = new StringBuffer();
        for (Integer[] row : path) {
            for(Integer item : row) {
                if (item == null) {
                    result.append("- ");
                }
                else {
                    result.append(item + " ");
                }
            }
            result.append("\n");
        }
        return result.toString();
    }

    @Override
    public boolean equals(Object o) {
        if (!(o instanceof Path)) {
            return false;
        }
        Path p = (Path)o;
        if (p.rows() != this.rows() || p.columns() != this.columns() || p.getNumOfPathFields() != this.getNumOfPathFields()) {
            return false;
        }
        for (int row = 0; row < this.rows(); row++) {
            for (int column = 0; column < this.columns(); column++) {
                Coordinates currentCoords = new Coordinates(column, row);
                if (get(currentCoords) == null ^ p.get(currentCoords) == null){
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 59 * hash + this.numOfPathFields;
        return hash;
    }
}
